﻿
using NewLife;
using NewLife.Log;
using System.Numerics;
using System.Security.Cryptography;
using YY.Admin.Application.Service.Config;
using YY.Admin.Core.Util;


namespace YY.Admin.Application.Service
{
    public class SysAuthService : ISysAuthService
    {
        private SysUser? _currentUser;
        public SysUser? CurrentUser => _currentUser;
        public event EventHandler<SysUser?>? UserChanged;
        private readonly ISysCacheService _sysCacheService;
        private readonly ISqlSugarDbContext _dbContext;
        private readonly ISysConfigService _sysConfigService;

        public SysAuthService(
            ISqlSugarDbContext dbContext,
            ISysCacheService sysCacheService,
            ISysConfigService sysConfigService) {
            _dbContext=dbContext;
            _sysCacheService=sysCacheService;
            _sysConfigService=sysConfigService;
        }
        public async Task<LoginOutput> LoginAsync(LoginInput request)
        {
            try
            {
                // 判断密码错误次数（缓存30分钟）
                var keyPasswordErrorTimes = $"{CacheConst.KeyPasswordErrorTimes}{request.Username}";
                var passwordErrorTimes = _sysCacheService.Get<int>(keyPasswordErrorTimes);
                var passwordMaxErrorTimes = await _sysConfigService.GetConfigValue<int>(ConfigConst.SysPasswordMaxErrorTimes);
                if (passwordMaxErrorTimes < 1) passwordMaxErrorTimes = 10;
                if (passwordErrorTimes > passwordMaxErrorTimes) {
                    return new LoginOutput
                    {
                        Success = false,
                        Message = "密码错误次数过多，账号已锁定，请半小时后重试！"
                    };
                }
                // 账号是否存在
                var user = await _dbContext.Db.Queryable<SysUser>().Includes(u => u.SysOrg).ClearFilter()
                    .WhereIF(request.TenantId > 0, u => (u.AccountType == AccountTypeEnum.SuperAdmin || u.TenantId == (request.TenantId)))
                    .WhereIF(!string.IsNullOrWhiteSpace(request.Username), u => u.Account.Equals(request.Username))
                    .WhereIF(!string.IsNullOrWhiteSpace(request.Username), u => u.Phone.Equals(request.Username)).FirstAsync();
                if (user == null)
                {
                    return new LoginOutput
                    {
                        Success = false,
                        Message = "账号不存在"
                    };
                }
                // 账号是否被冻结
                if (user.Status == StatusEnum.Disable)
                {
                    return new LoginOutput
                    {
                        Success = false,
                        Message = "账号已冻结"
                    };
                };

                if (VerifyPassword(request.Password, keyPasswordErrorTimes, passwordErrorTimes, user))
                {
                    _currentUser = user;
                    UserChanged?.Invoke(this, _currentUser);
                    return new LoginOutput
                    {
                        Success = true,
                        Message = "登录成功",
                        User = _currentUser,
                        Token = GenerateToken()
                    };
                }
                else {
                    return new LoginOutput
                    {
                        Success = false,
                        Message = "用户名或者密码不正确！"
                    };
                }
            }
            catch (Exception ex)
            {
                return new LoginOutput
                {
                    Success = false,
                    Message = $"登录失败：{ex.Message}"
                };
            }
        }
        public bool VerifyPassword(string password, string keyPasswordErrorTimes, int passwordErrorTimes, SysUser user)
        {
            // 国密SM2解密（密码传输SM2加密后的）
            password = CryptogramUtil.SM2Decrypt(password);
            if (CryptogramUtil.CryptoType == CryptogramEnum.MD5.ToString())
            {
                if (user.Password.Equals(CryptogramUtil.Encrypt(password)))return true;
            }
            else
            {
                if (CryptogramUtil.Decrypt(user.Password).Equals(password)) return true;
            }
            _sysCacheService.Set(keyPasswordErrorTimes, ++passwordErrorTimes, TimeSpan.FromMinutes(30));
            return false;
        }
        public async Task LogoutAsync()
        {
            await Task.Delay(100);
            _currentUser = null;
            UserChanged?.Invoke(this, null);
        }

        public async Task<bool> IsAuthenticatedAsync()
        {
            await Task.Delay(50);
            return _currentUser != null;
        }
        /// <summary>
        ///创建token
        /// </summary>
        /// <returns></returns>
        private string GenerateToken()
        {
            var bytes = new byte[32];
            using var rng = RandomNumberGenerator.Create();
            rng.GetBytes(bytes);
            return Convert.ToBase64String(bytes);
        }
    }
}
